﻿using EnvDTE;
using EnvDTE80;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Windows.Forms;

namespace UTGenerator
{
    public partial class ucConfiguracao : UserControl
    {      
        public ucConfiguracao()
        {
            InitializeComponent();
        }

        private DTE2 aplicacao;

        public DTE2 Aplicacao
        {
            get 
            {
                return aplicacao; 
            }
            set 
            {
                aplicacao = value;
            }
        }

        public void Inicializar()
        {
            Globals globais = aplicacao.Globals;

            Dictionary<string, string> colecao = new Dictionary<string, string>();

            colecao.Add("MicrosoftVisualStudioDebuggerVisualizersdll", @"C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\ReferenceAssemblies\v2.0\Microsoft.VisualStudio.DebuggerVisualizers.dll");
            colecao.Add("envdtedll", @"C:\Windows\assembly\GAC\EnvDTE\8.0.0.0__b03f5f7f11d50a3a\envdte.dll");
            colecao.Add("envdte80dll", @"C:\Windows\assembly\GAC\EnvDTE80\8.0.0.0__b03f5f7f11d50a3a\envdte80.dll");
            colecao.Add("envdte90dll", @"C:\Windows\assembly\GAC\EnvDTE90\9.0.0.0__b03f5f7f11d50a3a\envdte90.dll");
            colecao.Add("envdte100dll", @"C:\Windows\assembly\GAC_MSIL\EnvDTE100\10.0.0.0__b03f5f7f11d50a3a\envdte100.dll");
            colecao.Add("SystemXmldll", @"C:\Program Files\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\System.Xml.dll");
            colecao.Add("VSLangProjdll", @"C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\PublicAssemblies\VSLangProj.dll");
            colecao.Add("UTGeneratorVisualizerdll", @"C:\Users\<username>\Documents\Visual Studio 2010\Visualizers");

            foreach (KeyValuePair<string, string> par in colecao)
            {
                // persistencia
                if (!globais.get_VariableExists(par.Key))
                {
                    // nao existe- persiste os valores a partir da colecao 
                    globais[par.Key] = colecao[par.Key];
                    globais.set_VariablePersists(par.Key, true);
                }

                // referencias
                if (par.Key != "UTGeneratorVisualizerdll")
                {
                    // referencias
                    bool asmOk = true;

                    try
                    {
                        Assembly asm = Assembly.LoadFile(par.Value);
                        if (par.Key.ToLower() != asm.ManifestModule.Name.ToLower().Replace(".", ""))
                        {
                            asmOk = false;
                        }

                    }
                    catch
                    {
                        asmOk = false;
                    }

                    while (!asmOk)
                    {
                        Assembly asm = SelecionarArquivo(@"c:\"
                                    , "dll files (*.dll)|*.dll"
                                    , 1
                                    , string.Format("Please, select an assembly file of {0}", par.Key));

                        if (par.Key == asm.FullName)
                        {
                            globais[par.Key] = asm.Location;
                            globais.set_VariablePersists(par.Key, true);
                            asmOk = true;
                        }
                    }
                }
                else
                {
                    // saida
                    txtSaida.Text = globais[par.Key];
                }
            }
        }

        private void btnAbrir_Click(object sender, EventArgs e)
        {
            Assembly asm = SelecionarArquivo(@"c:\"
                                                    , "dll files (*.dll)|*.dll|exe files (*.exe)|*.exe"
                                                    , 2
                                                    , "Please, select an assembly file");

            if (asm != null)
            {
                Type[] tipos = asm.GetTypes();

                cboTipos.DataSource = tipos;
                cboTipos.Visible = true;
                btnGerar.Visible = true;
            }
        }

        private static Assembly SelecionarArquivo(string diretorioInicial
                                                , string filtro
                                                , int indiceFiltro
                                                , string titulo)
        {   
            OpenFileDialog openFileDialogAsm = new OpenFileDialog();

            Assembly asm = null;

            openFileDialogAsm.InitialDirectory = diretorioInicial;
            openFileDialogAsm.Filter = filtro;
            openFileDialogAsm.FilterIndex = indiceFiltro;
            openFileDialogAsm.RestoreDirectory = true;
            openFileDialogAsm.Title = titulo;

            if (openFileDialogAsm.ShowDialog() == DialogResult.OK)
            {
                string nomeArquivo = openFileDialogAsm.FileName;

                try
                {
                    asm = Assembly.LoadFrom(nomeArquivo);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error: " + ex.Message);
                }
            }

            return asm;
        }

        private void btnGerar_Click(object sender, EventArgs e)
        {
            
            Type tipo = ((System.Type)(cboTipos.SelectedValue));

            try
            {
                new Compilador().Gerar(tipo, aplicacao);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: " + ex.Message);
            }
        }

        private void btnSelecionar_Click(object sender, EventArgs e)
        {
            using (FolderBrowserDialog dlg = new FolderBrowserDialog()) 
            { 
                dlg.Description = "Select a folder"; 
                if (dlg.ShowDialog() == DialogResult.OK) 
                { 
                    txtSaida.Text = dlg.SelectedPath;
                    Globals globais = aplicacao.Globals;
                    globais["UTGeneratorVisualizerdll"] = dlg.SelectedPath;
                    globais.set_VariablePersists("UTGeneratorVisualizerdll", true);
                } 
            }
        }
    }
}
